﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections;
using System.Reflection;

namespace APIIT_BPEL_Server.Http_Layer
{
    public class Request_Dispatcher
    {
        private static CookieContainer container = new CookieContainer();

        private string createCookieString()
        {
            string cookieString = "";
            int temp = 0;
            Hashtable table = (Hashtable)container.GetType().InvokeMember("m_domainTable",
                                                                          BindingFlags.NonPublic |
                                                                          BindingFlags.GetField |
                                                                          BindingFlags.Instance,
                                                                          null,
                                                                          container,
                                                                          new object[] { });
            string tempSring = "";

            foreach (var key in table.Keys)
            {
                if (key.ToString().IndexOf('.', 0, 1) != -1)
                {
                    tempSring = key.ToString().Substring(1);
                }
                else
                {
                    tempSring = key.ToString();
                }
                foreach (Cookie cookie in container.GetCookies(new Uri(string.Format("http://{0}/", tempSring))))
                {
                    if (temp == 0)
                    {
                        cookieString = cookie.Name + "=" + cookie.Value + "=" + cookie.Domain;
                    }
                    else
                    {
                        cookieString = cookieString + ";" + cookie.Name + "=" + cookie.Value + "=" + cookie.Domain;
                    }
                    temp++;
                }
            }
            return cookieString;
        }

        private void createCookieContainer(string cookieString)
        {
            string[] cookiesArray = null;
            if (cookieString != string.Empty)
            {
                cookiesArray = Regex.Split(cookieString, ";");
            }
            string[] cookie;
            container = new CookieContainer();
            if (cookiesArray != null)
            {
                for (int i = 0; i < cookiesArray.Length; i++)
                {
                    cookie = Regex.Split(cookiesArray[i], "=");
                    container.Add(new Cookie(cookie[0].Trim(), cookie[1].Trim()) { Domain = cookie[2] });
                }
            }
            cookieString = "";
        }

        private HttpWebRequest createHttpGetRequest(string URI, string Parameters)
        {
            string finalURI;
            if (URI.IndexOf("?") != -1 && Parameters != "")
            {
                finalURI = URI + "?" + Parameters;
            }
            else
            {
                if (Parameters != "")
                {
                    finalURI = URI + "&" + Parameters;
                }
                else
                    finalURI = URI;
            }
            System.Net.HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(finalURI);
            req.CookieContainer = container;
            req.Proxy = new System.Net.WebProxy();
            req.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0";
            req.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-gsarcade-launch, */*";
            req.KeepAlive = true;
            req.AllowAutoRedirect = false;
            //req.TransferEncoding = "gzip, deflate";
            req.Referer = "http://webspace1.apiit.lk/gims/library/default.asp";
            return req;
        }

        private HttpWebRequest createHttpPostRequest(string URI, string Parameters)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(URI);
            req.CookieContainer = container;
            req.AllowAutoRedirect = false;
            req.Proxy = new System.Net.WebProxy();
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            req.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0";
            req.AllowAutoRedirect = false;
            req.KeepAlive = true;
            //req.TransferEncoding = "gzip, deflate";
            req.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-gsarcade-launch, */*";
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
            req.ContentLength = bytes.Length;
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);
            os.Close();
            return req;
        }

        public string doGet(string URI, string Parameters, string CookieString)
        {
            createCookieContainer(CookieString);
            HttpWebRequest request = createHttpGetRequest(URI, Parameters);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string tmp = "";
            string[] tmpArray;
            string location = "";

            while (response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.SeeOther)
            {
                response.Close();
                tmp = Regex.Split(response.ResponseUri.ToString(), "\\?")[0];
                tmpArray = Regex.Split(tmp, "/");
                location = response.Headers["Location"];

                if (location.Contains("http"))
                    //IndexOf("http") != -1)
                {

                    request = createHttpGetRequest(response.Headers["Location"], "");
                }
                else
                {
                    request = createHttpGetRequest(Regex.Split(tmp, tmpArray[tmpArray.Length - 1])[0] + response.Headers["Location"], "");
                }
                
                response = (HttpWebResponse)request.GetResponse();
            }

            System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
            return sr.ReadToEnd().Trim() + "===cookie===" + createCookieString();
        }

        public string doPost(string URI, string Parameters, string CookieString)
        {
            createCookieContainer(CookieString);
            HttpWebRequest request = createHttpPostRequest(URI, Parameters);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string tmp = "";
            string[] tmpArray;
            string location = "";
            while (response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.SeeOther)
            {
                response.Close();
                tmp = Regex.Split(response.ResponseUri.ToString(), "\\?")[0];
                tmpArray = Regex.Split(tmp, "/");
                // value = "";

                //for (int i = 0; i < tmpArray.Length; i++)
                //{
                //    if (tmpArray[i] != "") {
                //        if (i == 0)
                //        {
                //            value = value + tmpArray[i];
                //        }
                //        else
                //        {
                //            value = value + "===" + tmpArray[i];
                //        }
                //    }

                //}
                //tmpArray = Regex.Split(value,"===");
                string locationStr = "";
                location = response.Headers["Location"];
                if (location.Contains("http"))
                    //IndexOf("http") != -1)
               {
                    request = createHttpGetRequest(response.Headers["Location"], "");
                }
                else
                {
                    
                    if (response.Headers["Location"].Contains("/"))
                    {
                        locationStr = response.Headers["Location"];
                    }
                    else
                    {
                        locationStr = "/" + response.Headers["Location"];
                    }

                    string[] locationarr = Regex.Split(locationStr, "/");
                    if (locationarr.Length > 2)
                    {
                        request = createHttpGetRequest(Regex.Split(tmp, "/" + locationarr[1])[0] + locationStr, "");
                    }
                    else
                    {
                        request = createHttpGetRequest(Regex.Split(tmp, tmpArray[tmpArray.Length - 1])[0] + response.Headers["Location"], "");
                    }
                }
                response = (HttpWebResponse)request.GetResponse();
            }

            System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
            return sr.ReadToEnd().Trim() + "===cookie===" + createCookieString();
        }
    }
}